package com.itheima.train.manager.order.handler.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitmqProducer implements RabbitTemplate.ConfirmCallback {

    // 创建日志对象
    private Logger logger = LoggerFactory.getLogger(RabbitmqProducer.class) ;

    // 注入RabbitmqTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate ;

    // 发送消息
    public void sendMessage(String jsonData , String routingKey) {

        // 创建CorrelationData对象
        CorrelationData correlationData = new CorrelationData(jsonData)  ;

        // 设置回调函数
        rabbitTemplate.setConfirmCallback(this);

        // 消息的发送
        rabbitTemplate.convertAndSend("train_manager_ex", routingKey, jsonData , correlationData);
    }

    // 客户端的回调函数
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack) {
            logger.info("【发送消息成功了】--->" + correlationData.getId());
        }else {
            logger.info("【发送消息失败了】--->" + correlationData.getId());
        }
    }

}
